﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Core;
using SmartSapce.ServiceLocation;
using SmartSpace.WebForm;

namespace SmartSpace.WebForm.Shell
{
    public partial class _shell : System.Web.UI.Page
    {
        protected System.Web.UI.HtmlControls.HtmlGenericControl _ctlContainer;
        private Guid _applicationId;
        private Guid _navigationId;
        private string _viewsString;
        private List<ViewInfo> _viewInfos = new List<ViewInfo>();
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["__id"]))
            {
                _applicationId = new Guid(Request.QueryString["__id"]);

                if (!string.IsNullOrEmpty(Request.QueryString["nid"]))
                {
                    _navigationId = new Guid(Request.QueryString["nid"]);
                }

                if(!string.IsNullOrEmpty(Request.QueryString["__views"]))
                {
                    _viewsString = Request.QueryString["__views"];
                }

                ICoreService service = ServiceLocator.Get<ICoreService>();
                Application application = service.GetApplication(_applicationId);
                User user = service.GetUser(User.Identity.Name);
                Theme theme = service.GetTheme(application.ThemeId.Value);
                List<Shortcut> shortcuts = service.GetUserShortcuts(application.Id, user.Id);
                List<Navigation> navigations = service.GetUserNavigations(application.Id, user.Id);
                List<Application> applications = service.GetApplications();

                System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(Server.MapPath("~/" + theme.Package));

                ITheme themeInstance = (ITheme)assembly.CreateInstance(theme.Name);
                IMainPanel mainPanel = themeInstance.GetMainPanel(this);

                Control mycontrol = mainPanel.GetContentView();
                _ctlContainer.Controls.Add(mycontrol);

                mainPanel.GetHeaderPanel().Initiate(shortcuts, applications, application, user);
                mainPanel.GetNavigatePanel().Initiate(navigations, shortcuts);

                mainPanel.GetHeaderPanel().Logoff += new LogoffEventHandler(_shell_Logoff);
                mainPanel.GetNavigatePanel().Navigating += _shell_Navigating;

                if (!string.IsNullOrEmpty(_viewsString))
                {
                    _viewsString = Encoding.UTF8.GetString(Convert.FromBase64String(_viewsString));
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(?<path>[^\\[\\]]*)\\[(?<arguments>[^\\[\\]]*)\\]");
                    System.Text.RegularExpressions.MatchCollection matchs = regex.Matches(_viewsString);
                    foreach (System.Text.RegularExpressions.Match match in matchs)
                    {
                        _viewInfos.Add(new ViewInfo
                        {
                            VirtualPath = match.Groups["path"].Value,
                            Arguments = match.Groups["arguments"].Value
                        });
                    }
                    string virtualPath = _viewInfos.Last().VirtualPath;
                    string argumentString = _viewInfos.Last().Arguments;
                    System.Collections.Specialized.NameValueCollection arguments = HttpUtility.ParseQueryString(argumentString.Replace(',', '&'));

                    Navigation curNavigation = service.GetNavigation(_navigationId);
                    Guid viewId = new Guid(curNavigation.Url.Replace("v:>>", string.Empty));
                    ModuleView view = service.GetView(viewId);
                    System.Reflection.Assembly moduleAssembly = System.Reflection.Assembly.LoadFile(Server.MapPath("~/" + view.Module.Package));

                    AppModule moduleInstance = (AppModule)moduleAssembly.CreateInstance(view.Module.Name);
                    SubView viewInstance = moduleInstance.GetView(this, virtualPath);
                    mainPanel.GetWorkAreaPanel().SwitchView(viewInstance);
                    viewInstance.OnShown(arguments);
                    viewInstance.SwitchView += viewInstance_SwitchView;
                }
                else if (_navigationId != Guid.Empty)
                {
                    Navigation curNavigation = service.GetNavigation(_navigationId);
                    Guid viewId = new Guid(curNavigation.Url.Replace("v:>>", string.Empty));
                    ModuleView view = service.GetView(viewId);
                    System.Reflection.Assembly moduleAssembly = System.Reflection.Assembly.LoadFile(Server.MapPath("~/" + view.Module.Package));

                    AppModule moduleInstance = (AppModule)moduleAssembly.CreateInstance(view.Module.Name);
                    AppView viewInstance = moduleInstance.GetView(this, view);
                    mainPanel.GetWorkAreaPanel().SwitchView(viewInstance);
                    viewInstance.SwitchView += viewInstance_SwitchView;
                }
            }
            else
            {

            }
        }

        void viewInstance_SwitchView(object sender, SwitchEventArgs e)
        {
            string originalViewString = string.Empty;

            foreach (var viewInfo in _viewInfos)
            {
                originalViewString += string.Format("{0}[{1}]/",
                    viewInfo.VirtualPath,
                    viewInfo.Arguments);
            }

            originalViewString += string.Format("{0}[{1}]/",
                e.VirtualPath,
                e.Arguments);

            originalViewString = Convert.ToBase64String(Encoding.UTF8.GetBytes(originalViewString));

            Response.Redirect(Request.Url.AbsolutePath + string.Format("?id={0}&nid={1}&__views={2}",
                _applicationId,
                _navigationId,
                originalViewString));
        }

        void _shell_Navigating(object sender, NavigatingEventArgs e)
        {
            Response.Redirect(Request.Url.AbsolutePath + string.Format("?id={0}&nid={1}", _applicationId, e.Navigation.Id.ToString()));
        }

        void _shell_Logoff(object sender, LogoffEventArgs e)
        {
            Response.Redirect("~/_logoff.aspx");
        }
    }
}
